package com.game.logic.task;

import com.coment.cfg.luban.Tables;
import com.coment.cfg.luban.task.TaskCfg;
import com.coment.po.UserTaskInfo;
import com.game.dao.user.task.UserTaskInfoDao;
import com.game.logic.core.ranking.RakingService;
import com.game.logic.items.prop.PropService;
import com.xs.action.exection.ActionException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/// 任务系统
@Slf4j
@Service
public class UserTaskInfoService {
    @Resource
    private PropService propService;
    @Resource
    public UserTaskInfoDao userTaskInfoDao;

    /// 领取奖励
    public void obtainReward(Integer userInfoId, Integer taskId) {
        TaskCfg taskCfg = Tables.cfg.get_tbtaskcfg().get(taskId);
        int num = taskCfg.num;

        UserTaskInfo userTaskInfo = userTaskInfoDao.findUserTaskInfoByUserInfoIdAndTaskId(userInfoId, taskId);
        userTaskInfo.quantityClaimed++;

        if (userTaskInfo.quantityClaimed > num) {
            throw new ActionException("奖励已达上限");
        }

        if (userTaskInfo.quantityClaimed > userTaskInfo.completionCount) {
            throw new ActionException("请继续做任务");
        }

        propService.obtainOrUpgrade(userInfoId, taskCfg.rewardItem);
        userTaskInfoDao.save(userTaskInfo);
    }

    /// 完成任务
    @Async
    public void tryCompleteTask(Integer level, List<RakingService.RankInfo<Object>> userInfoIdRanking) {
        log.info("开始尝试完成任务");
        List<TaskCfg> cfg = Tables.cfg.get_tbtaskcfg().get_dataList().stream().filter(taskCfg -> taskCfg.pveLV == level).toList();
        for (RakingService.RankInfo<Object> rankInfo : userInfoIdRanking) {
            Integer userInfoId = (Integer) rankInfo.id();
            long rank = rankInfo.rank();

            if (!cfg.isEmpty()) {
                for (TaskCfg taskCfg : cfg) {
                    int taskId = taskCfg.id;
                    if (taskCfg.ranking.contains((int) rank)) {
                        UserTaskInfo userTaskInfo = userTaskInfoDao.findUserTaskInfoByUserInfoIdAndTaskId(userInfoId, taskId);
                        userTaskInfo.completionCount++;
                        log.debug("{}完成任务{}-{}", userInfoId, taskId, userTaskInfo.completionCount);
                        userTaskInfoDao.save(userTaskInfo);
                        obtainReward(userInfoId, taskId);
                    }
                }
            }
        }
    }
}
